const express = require('express');
const router = express.Router();
const StudentActivity = require('../../models/SjoinActivity/SjoinActivity');
const Activities = require('../../models/activities/activities');

const { Op } = require('sequelize');

// 学生报名活动
router.post('/joinActivity', async (req, res) => {
  try {
    const { student_id, activity_id } = req.body;

    // 验证必填字段
    if (!student_id || !activity_id) {
      return res.status(400).json({
        success: false,
        message: '缺少必要参数'
      });
    }

    // 检查活动是否存在
    const activity = await Activities.findByPk(activity_id);
    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动不存在'
      });
    }

    // 检查报名截止时间
    if (new Date() > new Date(activity.registration_deadline)) {
      return res.status(400).json({
        success: false,
        message: '活动报名已截止'
      });
    }

    // 检查是否已报名
    const existingRegistration = await StudentActivity.findOne({
      where: {
        student_id,
        activity_id
      }
    });

    if (existingRegistration) {
      return res.status(400).json({
        success: false,
        message: '已经报名过该活动'
      });
    }

    // 检查报名人数是否已满
    const registeredCount = await StudentActivity.count({
      where: {
        activity_id,
        status: 'registered'
      }
    });

    if (registeredCount >= activity.max_participants) {
      return res.status(400).json({
        success: false,
        message: '活动报名人数已满'
      });
    }

    // 创建报名记录
    const registration = await StudentActivity.create({
      student_id,
      activity_id,
      status: 'registered',
      register_time: new Date()
    });

    res.status(201).json({
      success: true,
      message: '报名成功',
      data: registration
    });
  } catch (error) {
    console.error('报名失败:', error);
    res.status(500).json({
      success: false,
      message: '报名失败',
      error: error.message
    });
  }
});



module.exports = router;
